package com.dlwx.parttimetalent.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.LateOrderAdapter;
import com.dlwx.parttimetalent.bean.OrderBean;
import com.dlwx.parttimetalent.bean.UnReadBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.PositionInter;
import com.dlwx.parttimetalent.ui.OrderDetailActivity;
import com.dlwx.parttimetalent.ui.OrderEmployeActivity;
import com.dlwx.parttimetalent.ui.OrderMasterActivity;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.views.MyProgressLoading;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

public class OneFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    Unbinder unbinder;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    private LateOrderAdapter mAdapter;
    private int page=1;
    private LRecyclerViewAdapter lRecyclerViewAdapter;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private OnFragmentInteractionListener mListener;
    private MyProgressLoading loadingDialog;
    private TextView tv_refuse1,tv_refuse;
    private Badge badgeView;
    private Badge badgeView1;
    private Badge badgeView2;

    //    private OrderMasterAdapter mAdapter;
//    private ArrayList<ContactsBean> mDatas;
    public OneFragment() {
        // Required empty public constructor
    }
    // TODO: Rename and change types and number of parameters
    public static OneFragment newInstance(String param1, String param2) {
        OneFragment fragment = new OneFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
//        getDatas();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.i("onresume");
        int gyNum = (int) SPUtils.get(getActivity(), Constant.MSG_GY, 0);
        int spNum = (int) SPUtils.get(getActivity(), Constant.MSG_SP, 0);
        int pjNum = (int) SPUtils.get(getActivity(), Constant.MSG_PJ, 0);
        if (gyNum > 0) {
            badgeView.setGravityOffset(20,5,true).setBadgeNumber(gyNum);
        }else{
            badgeView.setGravityOffset(20,5,true).setBadgeNumber(0);
        }
        if (spNum > 0) {
            badgeView1.setGravityOffset(20,5,true).setBadgeNumber(spNum);
        }else{
            badgeView1.setGravityOffset(20,5,true).setBadgeNumber(0);
        }
        if (pjNum > 0) {
            badgeView2.setGravityOffset(40,5,true).setBadgePadding(4,true).setBadgeNumber(-1);
        }else{
            badgeView2.setGravityOffset(20,5,true).setBadgeNumber(0);
        }
        refresh();
        getUnReadMsg();
    }

    private void getDatas() {
        OkgoUtil.post(Http.LatelyOrder,getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        OrderBean parentBean= DealResult.getInstance().dealDatas(getActivity(),response
                                ,new TypeToken<OrderBean>() {}.getType());
                        if(parentBean==null){return;}
                        if(parentBean.getCode()== Constant.SUCESS||parentBean.getCode()== Constant.EMPTY){
                            setDatas(parentBean.getBody());
                        }else {
                            recyclerView.refreshComplete(mAdapter.getItemCount());
                            ToastUtils.toastForShort(getActivity(),parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        recyclerView.refreshComplete(mAdapter.getItemCount());
                        loadingDialog.dismiss();
                    }
                });
    }

    private void setDatas(List<OrderBean.BodyBean> body) {
        mAdapter.addAll(body);
        if(recyclerView!=null){
            recyclerView.refreshComplete(mAdapter.getItemCount());
        }
    }

    private void initView() {

        loadingDialog = new MyProgressLoading(getActivity(), R.style.DialogStyle);
        tvMiddleTitle.setText("我的订单");
        tvMiddleTitle.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter=new LateOrderAdapter(getActivity(), new PositionInter() {
            @Override
            public void callBack(int position) {
                if(position==Constant.ONE_ORDER){
                    msgNumListenner.refreshMsgNum();
                }else{
                    refresh();
                }
            }
        });
        mAdapter.setDataList(new ArrayList<OrderBean.BodyBean>());
        lRecyclerViewAdapter=new LRecyclerViewAdapter(mAdapter);
        //divider
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.size_1)
//                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.bg)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(true);
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        addHeader(lRecyclerViewAdapter);
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int orderId=mAdapter.getDataList().get(position).getOrderid();
                int orderType=mAdapter.getDataList().get(position).getOrderType();
                Intent i=new Intent(getActivity(), OrderDetailActivity.class);
                i.putExtra("id",orderId+"");
                i.putExtra("orderType",orderType+"");
                startActivity(i);
            }
        });
    }

    private void addHeader(LRecyclerViewAdapter lRecyclerViewAdapter) {
        CommonHeader header=new CommonHeader(getActivity(),R.layout.header_one_fragment);
        RelativeLayout tvMasterAll=header.findViewById(R.id.tv_master_all);
        tv_refuse=header.findViewById(R.id.tv_refuse);
        TextView tv_accept=header.findViewById(R.id.tv_accept);
        TextView tv_evaluate=header.findViewById(R.id.tv_evaluate);
        final Intent i=new Intent(getActivity(), OrderMasterActivity.class);
        tv_refuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i.putExtra("flag",1);
                startActivity(i);
            }
        });
        tv_accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i.putExtra("flag",2);
                startActivity(i);
            }
        });
        tv_evaluate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i.putExtra("flag",3);
                startActivity(i);
            }
        });
//
         tv_refuse1=header.findViewById(R.id.tv_refuse1);
        TextView tv_accept1=header.findViewById(R.id.tv_accept1);
        TextView tv_evaluate1=header.findViewById(R.id.tv_evaluate1);
        final Intent i1=new Intent(getActivity(), OrderEmployeActivity.class);
        tv_refuse1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i1.putExtra("flag",1);
                startActivity(i1);
            }
        });
        tv_accept1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i1.putExtra("flag",2);
                startActivity(i1);
            }
        });
        tv_evaluate1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i1.putExtra("flag",3);
                startActivity(i1);
            }
        });
        tvMasterAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), OrderMasterActivity.class));
            }
        });
        RelativeLayout tvEmployeAll=header.findViewById(R.id.tv_employe_all);
        tvEmployeAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), OrderEmployeActivity.class));
            }
        });
        badgeView=new QBadgeView(getActivity()).bindTarget(tv_refuse);
        badgeView1=new QBadgeView(getActivity()).bindTarget(tv_refuse1);
        badgeView2=new QBadgeView(getActivity()).bindTarget(tv_evaluate);

        lRecyclerViewAdapter.addHeaderView(header);
    }
    private void refresh(){
        page=1;
        mAdapter.clear();
        lRecyclerViewAdapter.notifyDataSetChanged();
        getDatas();
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        msgNumListenner= (MsgNumListenner) context;
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    private MsgNumListenner msgNumListenner;
    public interface MsgNumListenner {
        // TODO: Update argument type and name
        void refreshMsgNum();
    }

    private void getUnReadMsg() {
        OkgoUtil.post(Http.GetUserUnread, getActivity())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        UnReadBean parentBean = DealResult.getInstance().dealDatas(getActivity()
                                , response, new TypeToken<UnReadBean>() {
                                }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        int code = parentBean.getCode();
                        if (code == Constant.SUCESS) {
                            UnReadBean.BodyBean bean = parentBean.getBody();
                            int orderNum=bean.getOrdernum();
                            int sysNum=bean.getSysnum();
                            int tradeNum=bean.getTradenum();
                            int gyNum=bean.getGynum();
                            int spNum=bean.getSpnum();
                            SPUtils.put(getActivity(),Constant.MSG_O,orderNum);
                            SPUtils.put(getActivity(),Constant.MSG_S,sysNum);
                            SPUtils.put(getActivity(),Constant.MSG_T,tradeNum);
                            SPUtils.put(getActivity(),Constant.MSG_SP,spNum);
                            SPUtils.put(getActivity(),Constant.MSG_GY,gyNum);
                            if (gyNum > 0) {
                                badgeView.setGravityOffset(20,5,true).setBadgeNumber(gyNum);
                            }else{
                                badgeView.setGravityOffset(20,5,true).setBadgeNumber(0);
                            }
                            if (spNum > 0) {
                                badgeView1.setGravityOffset(20,5,true).setBadgeNumber(spNum);
                            }else{
                                badgeView1.setGravityOffset(20,5,true).setBadgeNumber(0);
                            }
                        } else {
                        }
//                        ToastUtils.toastForShort(MainActivity.this, parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        loadingDialog.dismiss();
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(), getString(R.string.bad_net));
                    }
                });
    }
}
